import { createServer } from 'http';
import fs from 'fs/promises';
import path from 'path';

// TypeScript接口定义
interface User {
  id: number;
  name: string;
  email: string;
}

// 模拟数据库
class UserDatabase {
  private users: User[] = [
    { id: 1, name: 'John Doe', email: 'john@example.com' },
    { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
  ];

  async getUsers(): Promise<User[]> {
    // 模拟异步操作
    await new Promise(resolve => setTimeout(resolve, 100));
    return [...this.users];
  }

  async getUserById(id: number): Promise<User | null> {
    await new Promise(resolve => setTimeout(resolve, 100));
    return this.users.find(user => user.id === id) || null;
  }
}

// 创建HTTP服务器
async function startServer() {
  const db = new UserDatabase();
  const port = process.env.PORT || 3000;

  const server = createServer(async (req, res) => {
    // 设置响应头
    res.setHeader('Content-Type', 'application/json');
    
    try {
      // 处理路由
      if (req.url === '/users' && req.method === 'GET') {
        const users = await db.getUsers();
        res.statusCode = 200;
        res.end(JSON.stringify(users));
      } 
      else if (req.url?.match(/^\/users\/(\d+)$/) && req.method === 'GET') {
        const id = parseInt(req.url.split('/')[2], 10);
        const user = await db.getUserById(id);
        
        if (user) {
          res.statusCode = 200;
          res.end(JSON.stringify(user));
        } else {
          res.statusCode = 404;
          res.end(JSON.stringify({ message: 'User not found' }));
        }
      }
      else {
        res.statusCode = 404;
        res.end(JSON.stringify({ message: 'Route not found' }));
      }
    } catch (error) {
      res.statusCode = 500;
      res.end(JSON.stringify({ message: 'Server error' }));
    }
  });

  // 启动服务器
  server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
    console.log('Available routes:');
    console.log('GET /users - List all users');
    console.log('GET /users/:id - Get a specific user');
  });
}

// 启动应用
startServer().catch(console.error);
